package com.hup.minicontroller.server.service;


import android.content.Context;
import android.media.SoundPool;
import android.util.Log;

import com.hup.minicontroller.common.framework.SubThreadHandler;
import com.hup.minicontroller.server.R;
import com.hup.minicontroller.server.ServerApplication;

import java.util.ArrayList;

/**
 * 音效服务
 *
 * @author hugan
 * @date 2021/5/11
 */
public class SoundService {
    private static final String TAG = SoundService.class.getSimpleName();

    private final SubThreadHandler subThreadHandler;
    private final SoundPool soundPool;
    /**
     * R.raw.资源id,用于播放时[soundPool.play(index + 1)]
     */
    private final ArrayList<Integer> resourcesIds;

    public SoundService() {
        subThreadHandler = ServerApplication.getBean(SubThreadHandler.class);
        SoundPool.Builder builder = new SoundPool.Builder();
        builder.setMaxStreams(4);
        soundPool = builder.build();
        soundPool.setOnLoadCompleteListener((soundPool1, sampleId, status) -> {
            //Log.i(TAG, String.format(Locale.getDefault(), "SoundService:%d,%d ", sampleId, status));
            if (1 == sampleId) {
                //启动音效
                soundPool.setOnLoadCompleteListener(null);
                play(R.raw.boot);
            }
        });
        resourcesIds = new ArrayList<>();
        resourcesIds.add(R.raw.boot);
        resourcesIds.add(R.raw.shutdown);
        resourcesIds.add(R.raw.online);
        resourcesIds.add(R.raw.offline);
        Context context = ServerApplication.getContext();
        //加载音效,soundPool.load的返回值是[音效id/num,起始于1,按加载顺序递增的值]
        for (Integer resourceId : resourcesIds) soundPool.load(context, resourceId, 1);
    }

    /**
     * 播放音效
     *
     * @param resourcesId 如:R.raw.boot
     */
    public void play(int resourcesId) {
        int index = resourcesIds.indexOf(resourcesId) + 1;
        if (index == 0) {
            Log.e(TAG, "play: resourcesId异常:" + resourcesId, new Throwable());//Throwable用于定位异常代码
            return;
        }
        subThreadHandler.post(() -> soundPool.play(index, 1, 1, 1, 0, 1));
    }

    public void doTerminate() {
        soundPool.release();
    }

}
